import axios from 'axios'
import { getToken, removeToken } from './storage'
import history from './history'
import { message } from 'antd'
import { Console } from 'console'
const instance = axios.create({
  baseURL: 'http://geek.itheima.net/',
  timeout: 5000,
})
console.log(getToken())

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    const tokenStr = getToken() as any
    if (tokenStr) {
      config.headers!.Authorization = 'Bearer ' + JSON.parse(tokenStr).token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    console.dir(error)
    if (error.response && error.response.status === 401) {
      removeToken()
      history.push('/login')
      message.error('登录失效')
    }
    return Promise.reject(error)
  }
)

export default instance
